package com.shinewind.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.shinewind.gateway.result.Result;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.*;

@Configuration
public class GateWayConfig {
    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GateWayConfig(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    //配置限流的异常处理
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    //配置初始化的限流、熔断参数
    @PostConstruct
    public void initGatewayRules(){
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("modelPlayerIndex") //路由名称
                        .setCount(100)  //数量
                        .setIntervalSec(10) //每秒
        );
        rules.add(new GatewayFlowRule("modelPlayerInfo") //路由名称
                        .setCount(100)  //数量
                        .setIntervalSec(10) //每秒
        );
        rules.add(new GatewayFlowRule("modelPlayerSearch") //路由名称
                .setCount(100)  //数量
                .setIntervalSec(10) //每秒
        );
        rules.add(new GatewayFlowRule("modelPlayerSso") //路由名称
                .setCount(100)  //数量
                .setIntervalSec(10) //每秒
        );
        rules.add(new GatewayFlowRule("modelPlayerPayment") //路由名称
                .setCount(100)  //数量
                .setIntervalSec(10) //每秒
        );
        //加载网关限流规则
        GatewayRuleManager.loadRules(rules);

        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(new DegradeRule("modelPlayerIndex")
                .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) // 异常比率模式(秒级)
                .setCount(0.5) // 异常比率阈值
                .setTimeWindow(2) // 熔断降级时间
                .setMinRequestAmount(1000) //并发数
        );
        degradeRules.add(new DegradeRule("modelPlayerInfo")
                .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) // 异常比率模式(秒级)
                .setCount(0.5) // 异常比率阈值
                .setTimeWindow(2) // 熔断降级时间
                .setMinRequestAmount(1000) //并发数
        );
        degradeRules.add(new DegradeRule("modelPlayerSearch")
                .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) // 异常比率模式(秒级)
                .setCount(0.5) // 异常比率阈值
                .setTimeWindow(2) // 熔断降级时间
                .setMinRequestAmount(1000) //并发数
        );
        degradeRules.add(new DegradeRule("modelPlayerSso")
                .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) // 异常比率模式(秒级)
                .setCount(0.5) // 异常比率阈值
                .setTimeWindow(2) // 熔断降级时间
                .setMinRequestAmount(1000) //并发数
        );
        degradeRules.add(new DegradeRule("modelPlayerPayment")
                .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) // 异常比率模式(秒级)
                .setCount(0.5) // 异常比率阈值
                .setTimeWindow(2) // 熔断降级时间
                .setMinRequestAmount(1000) //并发数
        );
        // 加载熔断规则
        DegradeRuleManager.loadRules(degradeRules);
    }

    //初始化限流过滤器
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    //自定义限流异常页面
    @PostConstruct
    public void initBlockHandlers(){
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                return ServerResponse.status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromObject(Result.error(HttpStatus.SERVICE_UNAVAILABLE.value(),
                                    false,"服务正忙")));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

    @Bean
    public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes ()
                //home模块api
                .route (r -> r.path ("/index/model/**")
                        .filters (f -> f.dedupeResponseHeader("Access-Control-Allow-Origin","RETAIN_UNIQUE"))
                        .uri ("lb://modelPlayerIndex")
                        .id ("modelPlayerIndex")
                        .order(2)
                )
                //info模块api
                .route (r -> r.path ("/modelEvaluating/**","/modelDetail/**",
                                    "/user/**","/userInfo/**")
                        .filters (f -> f.dedupeResponseHeader("Access-Control-Allow-Origin","RETAIN_UNIQUE"))
                        .uri ("lb://modelPlayerInfo")
                        .id ("modelPlayerInfo")
                )
                //payment模块api
                .route(r -> r.path("/payment/**")
                        .filters (f -> f.dedupeResponseHeader("Access-Control-Allow-Origin","RETAIN_UNIQUE"))
                        .uri("lb://modelPlayerPayment")
                        .id("modelPlayerPayment")
                )
                //search模块api
                .route(r -> r.path("/index/search/**")
                        .filters (f -> f.dedupeResponseHeader("Access-Control-Allow-Origin","RETAIN_UNIQUE"))
                        .uri("lb://modelPlayerSearch")
                        .id("modelPlayerSearch")
                )
                //sso模块
                .route(r -> r.path("/sso/**")
                        .filters (f -> f.dedupeResponseHeader("Access-Control-Allow-Origin","RETAIN_UNIQUE"))
                        .uri("lb://modelPlayerSso")
                        .id("modelPlayerSso")
                        .order(1)
                )
                //admin模块
                .route(r -> r.path("/admin/**")
                        .filters (f -> f.dedupeResponseHeader("Access-Control-Allow-Origin","RETAIN_UNIQUE"))
                        .uri("lb://modelPlayerAdmin")
                        .id("modelPlayerAdmin")
                        .order(1)
                )
                .build ();
    }


}
